<template>
  <div>
    <el-row :gutter="20" class="stat-cards">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" class="stat-card">
        <el-card shadow="hover" class="stat-card-inner" v-loading="loading.dashboard">
          <div class="stat-content">
            <div class="stat-header">
              <i class="el-icon-user stat-icon" style="color: #1ba784; background-color: rgba(27, 167, 132, 0.1)"/>
              <span class="stat-title">{{ isAdmin ? $t('home.totalUsers') : isTeacher ? $t('home.todayCourses') : $t('home.totalCourses') }}</span>
            </div>
            <div class="stat-value">{{ isTeacher ? dashboardData.todayCourseCount : dashboardData.totalCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" class="stat-card">
        <el-card shadow="hover" class="stat-card-inner" v-loading="loading.dashboard">
          <div class="stat-content">
            <div class="stat-header">
              <i class="el-icon-tickets stat-icon" style="color: #5e665b; background-color: rgba(94, 102, 91, 0.1)"/>
              <span class="stat-title">{{ $t('home.leaveCount') }}</span>
            </div>
            <div class="stat-value">{{ dashboardData.leaveCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" class="stat-card">
        <el-card shadow="hover" class="stat-card-inner" v-loading="loading.dashboard">
          <div class="stat-content">
            <div class="stat-header">
              <i class="el-icon-link stat-icon" style="color: #f26b1f; background-color: rgba(242, 107, 31, 0.1)"/>
              <span class="stat-title">{{ $t('home.lateCount') }}</span>
            </div>
            <div class="stat-value">{{ dashboardData.lateCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" class="stat-card">
        <el-card shadow="hover" class="stat-card-inner" v-loading="loading.dashboard">
          <div class="stat-content">
            <div class="stat-header">
              <i class="el-icon-ship stat-icon" style="color: #c02c38; background-color: rgba(192, 44, 56, 0.1)"/>
              <span class="stat-title">{{ $t('home.absentCount') }}</span>
            </div>
            <div class="stat-value">{{ dashboardData.absentCount }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row" v-if="!isStudent">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card shadow="hover" class="chart-card" v-loading="loading.leaveChart">
          <div slot="header" class="chart-header">
            <span>{{ $t('home.leaveTrend') }}</span>
            <el-radio-group v-model="lineChartTimeRange" size="small" @change="updateLineChart">
              <el-radio-button label="week">{{ $t('home.lastWeek') }}</el-radio-button>
              <el-radio-button label="month">{{ $t('home.lastMonth') }}</el-radio-button>
              <el-radio-button label="all">{{ $t('home.all') }}</el-radio-button>
            </el-radio-group>
          </div>
          <div id="lineMain" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card shadow="hover" class="chart-card" v-loading="loading.leaveChart">
          <div slot="header" class="chart-header">
            <span>{{ $t('home.leaveDistribution') }}</span>
            <el-select v-model="pieChartType" size="small" @change="updatePieChart">
              <el-option :label="$t('home.byStatus')" value="status"></el-option>
              <el-option :label="$t('home.byType')" value="type"></el-option>
            </el-select>
          </div>
          <div id="pieMain" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row" v-if="!isStudent">
      <el-col :xs="24" :sm="24" :md="24" :lg="24">
        <el-card shadow="hover" class="chart-card" v-loading="loading.attendanceChart">
          <div slot="header" class="chart-header">
            <span>{{ $t('home.attendanceStats') }}</span>
            <el-radio-group v-model="attendanceTimeRange" size="small" @change="updateAttendanceChart">
              <el-radio-button label="week">{{ $t('home.lastWeek') }}</el-radio-button>
              <el-radio-button label="month">{{ $t('home.lastMonth') }}</el-radio-button>
            </el-radio-group>
          </div>
          <div id="barMain" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row" v-if="isStudent">
      <el-col :xs="24" :sm="24" :md="24" :lg="24">
        <el-card shadow="hover" class="chart-card" v-loading="loading.studentStats">
          <div slot="header" class="chart-header">
            <span>{{ $t('home.personalAttendance') }}</span>
          </div>
          <div class="student-stats">
            <el-row :gutter="20">
              <el-col :xs="12" :sm="12" :md="6" :lg="6" class="stat-item-col">
                <div class="stat-item">
                  <div class="stat-item-title">{{ $t('home.attendanceRate') }}</div>
                  <el-progress type="circle" :percentage="studentStats.attendanceRate || 0" :width="isMobile() ? 80 : 120" :stroke-width="isMobile() ? 6 : 8" :color="getColorForRate(studentStats.attendanceRate)"></el-progress>
                </div>
              </el-col>
              <el-col :xs="12" :sm="12" :md="6" :lg="6" class="stat-item-col">
                <div class="stat-item">
                  <div class="stat-item-title">{{ $t('home.lateRate') }}</div>
                  <el-progress type="circle" :percentage="studentStats.lateRate || 0" :width="isMobile() ? 80 : 120" :stroke-width="isMobile() ? 6 : 8" :color="getColorForRate(100 - studentStats.lateRate)"></el-progress>
                </div>
              </el-col>
              <el-col :xs="12" :sm="12" :md="6" :lg="6" class="stat-item-col">
                <div class="stat-item">
                  <div class="stat-item-title">{{ $t('home.absentRate') }}</div>
                  <el-progress type="circle" :percentage="studentStats.absentRate || 0" :width="isMobile() ? 80 : 120" :stroke-width="isMobile() ? 6 : 8" :color="getColorForRate(100 - studentStats.absentRate)"></el-progress>
                </div>
              </el-col>
              <el-col :xs="12" :sm="12" :md="6" :lg="6" class="stat-item-col">
                <div class="stat-item">
                  <div class="stat-item-title">{{ $t('home.leaveRate') }}</div>
                  <el-progress type="circle" :percentage="studentStats.leaveRate || 0" :width="isMobile() ? 80 : 120" :stroke-width="isMobile() ? 6 : 8" :color="getColorForRate(100 - studentStats.leaveRate)"></el-progress>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 新增：学生月度考勤趋势图表 -->
    <el-row :gutter="20" class="chart-row" v-if="isStudent">
      <el-col :xs="24" :sm="24" :md="24" :lg="24">
        <el-card shadow="hover" class="chart-card" v-loading="loading.studentMonthlyTrend">
          <div slot="header" class="chart-header">
            <span>{{ $t('home.monthlyTrend') }}</span>
          </div>
          <div id="studentTrendChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 新增：学生课程详细统计表格 -->
    <el-row :gutter="20" class="chart-row" v-if="isStudent">
      <el-col :xs="24" :sm="24" :md="24" :lg="24">
        <el-card shadow="hover" class="chart-card" v-loading="loading.studentCourses">
          <div slot="header" class="chart-header">
            <span>{{ $t('home.courseAttendanceDetails') }}</span>
          </div>
          <div class="responsive-table-container">
            <el-table :data="coursesStats" stripe style="width: 100%" size="mini" :class="{'mobile-table': isMobile()}">
              <el-table-column prop="courseName" :label="$t('course.name')" min-width="120"></el-table-column>
              <el-table-column prop="normalCount" :label="$t('home.normalAttendance')" min-width="90" align="center"></el-table-column>
              <el-table-column prop="lateCount" :label="$t('home.lateTimes')" min-width="80" align="center"></el-table-column>
              <el-table-column prop="absentCount" :label="$t('home.absentTimes')" min-width="80" align="center"></el-table-column>
              <el-table-column prop="leaveCount" :label="$t('home.leaveTimes')" min-width="80" align="center"></el-table-column>
              <el-table-column :label="$t('home.attendanceRate')" min-width="120">
                <template slot-scope="scope">
                  <el-progress :percentage="scope.row.attendanceRate" :stroke-width="isMobile() ? 12 : 18" :color="getColorForRate(scope.row.attendanceRate)"></el-progress>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { get } from '@/utils/request';
export default {
  name: "Home",
  data() {
    return {
      userInfo: null,
      isAdmin: false,
      isTeacher: false,
      isStudent: false,
      dashboardData: {
        totalCount: 0,
        todayCourseCount: 0,
        leaveCount: 0,
        lateCount: 0,
        absentCount: 0
      },
      studentStats: {
        attendanceRate: 0,
        lateRate: 0,
        absentRate: 0,
        leaveRate: 0
      },
      // 新增：学生月度考勤趋势数据
      monthlyTrendData: {
        months: [],
        attendanceRates: [],
        lateRates: [],
        absentRates: [],
        leaveRates: []
      },
      // 新增：学生课程详细统计
      coursesStats: [],
      studentTrendChart: null,
      lineChart: null,
      pieChart: null,
      barChart: null,
      resizeObserver: null,
      lineChartTimeRange: 'week',
      pieChartType: 'status',
      attendanceTimeRange: 'week',
      chartData: {
        lineData: {
          x: [],
          y: []
        },
        pieData: {
          status: [],
          type: []
        },
        barData: {
          xAxis: [],
          normal: [],
          leave: [],
          late: [],
          absent: []
        }
      },
      chartTheme: {
        colors: ['#1ba784', '#5e665b', '#f26b1f', '#c02c38', '#3498db', '#9b59b6', '#e74c3c', '#34495e']
      },
      loading: {
        dashboard: false,
        leaveChart: false,
        attendanceChart: false,
        studentStats: false,
        // 新增：学生月度趋势和课程统计的加载状态
        studentMonthlyTrend: false,
        studentCourses: false
      }
    }
  },
  methods: {
    getUserRole() {
      const userInfoStr = sessionStorage.getItem("userInfo");
      if (userInfoStr) {
        this.userInfo = JSON.parse(userInfoStr);
        if (this.userInfo && this.userInfo.roleName) {
          this.isAdmin = this.userInfo.roleName.includes('admin');
          this.isTeacher = this.userInfo.roleName.includes('teacher');
          this.isStudent = this.userInfo.roleName.includes('student');
        }
      }
    },
    
    getColorForRate(rate) {
      if (rate >= 80) return '#1ba784';
      if (rate >= 60) return '#f26b1f';
      return '#c02c38';
    },

    initCharts() {
      if (this.isStudent) {
        // 学生角色需要初始化趋势图
        this.initStudentTrendChart();
        return;
      }
      
      // 初始化图表DOM
      const lineChartDom = document.getElementById('lineMain');
      const pieChartDom = document.getElementById('pieMain');
      const barChartDom = document.getElementById('barMain');
      
      if (!lineChartDom || !pieChartDom || !barChartDom) {
        return;
      }
      
      // 初始化图表实例
      this.lineChart = echarts.init(lineChartDom);
      this.pieChart = echarts.init(pieChartDom);
      this.barChart = echarts.init(barChartDom);

      // 折线图配置
      const lineOption = {
        color: this.chartTheme.colors,
        title: {
          text: '',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: this.isMobile() ? 14 : 16
          }
        },
        grid: {
          top: this.isMobile() ? 60 : 40,
          left: this.isMobile() ? 40 : 50,
          right: this.isMobile() ? 10 : 30,
          bottom: this.isMobile() ? 60 : 50,
          containLabel: true
        },
        toolbox: {
          show: true,
          orient: this.isMobile() ? 'vertical' : 'horizontal',
          top: this.isMobile() ? 10 : 'top',
          right: this.isMobile() ? 5 : 'auto',
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const param = params[0];
            const people = this.$t('home.people');
            return `${param.name}<br/>${param.seriesName}: <strong>${param.value}</strong>${people}`;
          }.bind(this)
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            // 旋转45度
            rotate: 45,
            // 自动间隔
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: this.$t('home.people'),
          nameTextStyle: {
            padding: [0, 0, 0, 40]
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: this.$t('home.leavePeople'),
            data: [],
            type: 'line',
            smooth: true,
            showSymbol: !this.isMobile(),
            symbolSize: 6,
            lineStyle: {
              width: 3
            },
            areaStyle: {
              opacity: 0.2
            },
            markPoint: {
              data: [
                { type: 'max', name: this.$t('home.maxValue') },
                { type: 'min', name: this.$t('home.minValue') }
              ]
            }
          }
        ]
      };

      // 饼图配置
      const pieOption = {
        color: this.chartTheme.colors,
        title: {
          text: '',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: this.isMobile() ? 14 : 16
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            const people = this.$t('home.people');
            return `${params.seriesName} <br/>${params.name}: ${params.value}${people} (${params.percent}%)`;
          }.bind(this)
        },
        legend: {
          orient: 'horizontal',
          top: this.isMobile() ? 'bottom' : 'bottom',
          left: 'center',
          type: 'scroll',
          pageButtonPosition: 'end',
          textStyle: {
            fontSize: this.isMobile() ? 12 : 14
          }
        },
        series: [
          {
            name: this.$t('home.leavePeople'),
            type: 'pie',
            radius: this.isMobile() ? ['35%', '60%'] : ['40%', '70%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 6,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: !this.isMobile(),
              formatter: function(params) {
                return `${params.name}: ${params.value}${this.$t('home.people')}\n${params.percent}%`;
              }.bind(this)
            },
            emphasis: {
              label: {
                show: true,
                fontSize: this.isMobile() ? 14 : 16,
                fontWeight: 'bold'
              },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            labelLine: {
              show: !this.isMobile()
            },
            data: [{name: this.$t('common.loading'), value: 100}]
          }
        ]
      };

      // 柱状图配置
      const barOption = {
        color: this.chartTheme.colors,
        title: {
          text: '',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: this.isMobile() ? 14 : 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}${this.$t('home.people')}<br/>`;
            });
            return result;
          }.bind(this)
        },
        legend: {
          data: [
            this.$t('home.normal'), 
            this.$t('home.leave'), 
            this.$t('home.late'), 
            this.$t('home.absent')
          ],
          top: 'bottom'
        },
        grid: {
          top: this.isMobile() ? 60 : 40,
          left: this.isMobile() ? 40 : 50,
          right: this.isMobile() ? 10 : 30,
          bottom: this.isMobile() ? 80 : 60,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            rotate: 45,
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: this.$t('home.percentage'),
          min: 0,
          max: 100,
          nameTextStyle: {
            padding: this.isMobile() ? [0, 0, 0, 0] : [0, 0, 0, 40],
            fontSize: this.isMobile() ? 10 : 12
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: this.$t('home.normal'),
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: []
          },
          {
            name: this.$t('home.leave'),
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: []
          },
          {
            name: this.$t('home.late'),
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: []
          },
          {
            name: this.$t('home.absent'),
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: []
          }
        ]
      };

      // 初始化图表配置
      this.lineChart.setOption(lineOption);
      this.pieChart.setOption(pieOption);
      this.barChart.setOption(barOption);
      
      // 等待页面加载后，加载图表数据
      this.$nextTick(() => {
        // 加载柱状图
        this.updateAttendanceChart();
        
        // 加载请假分布数据（饼图）
        this.updatePieChart();
        
        // 加载请假趋势数据（折线图）
        this.updateLineChart();
      });

      // 使用ResizeObserver监听容器尺寸变化
      this.resizeObserver = new ResizeObserver(() => {
        this.updateChartOptions();
        this.lineChart.resize();
        this.pieChart.resize();
        this.barChart.resize();
      });

      // 监听图表容器
      this.resizeObserver.observe(lineChartDom);
      this.resizeObserver.observe(pieChartDom);
      this.resizeObserver.observe(barChartDom);
    },

    // 新增：初始化学生月度趋势图表
    initStudentTrendChart() {
      const trendChartDom = document.getElementById('studentTrendChart');
      if (!trendChartDom) return;
      
      this.studentTrendChart = echarts.init(trendChartDom);
      
      const option = {
        color: this.chartTheme.colors,
        title: {
          text: '',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: this.isMobile() ? 14 : 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: [
            this.$t('home.attendanceRate'), 
            this.$t('home.lateRate'), 
            this.$t('home.absentRate'), 
            this.$t('home.leaveRate')
          ],
          top: this.isMobile() ? 'bottom' : 'bottom',
          left: 'center',
          itemWidth: this.isMobile() ? 12 : 15,
          itemHeight: this.isMobile() ? 8 : 10,
          textStyle: {
            fontSize: this.isMobile() ? 10 : 12
          }
        },
        grid: {
          top: this.isMobile() ? 40 : 50,
          left: this.isMobile() ? 40 : 50,
          right: this.isMobile() ? 15 : 30,
          bottom: this.isMobile() ? 60 : 60,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.monthlyTrendData.months,
          axisLabel: {
            rotate: this.isMobile() ? 45 : 0,
            interval: this.isMobile() ? 'auto' : 0,
            fontSize: this.isMobile() ? 10 : 12
          }
        },
        yAxis: {
          type: 'value',
          name: this.$t('home.percentage'),
          min: 0,
          max: 100,
          nameTextStyle: {
            padding: this.isMobile() ? [0, 0, 0, 0] : [0, 0, 0, 40],
            fontSize: this.isMobile() ? 10 : 12
          },
          axisLabel: {
            fontSize: this.isMobile() ? 10 : 12
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: this.$t('home.attendanceRate'),
            data: this.monthlyTrendData.attendanceRates,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: this.isMobile() ? 4 : 6,
            lineStyle: {
              width: this.isMobile() ? 2 : 3
            }
          },
          {
            name: this.$t('home.lateRate'),
            data: this.monthlyTrendData.lateRates,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: this.isMobile() ? 4 : 6,
            lineStyle: {
              width: this.isMobile() ? 2 : 3
            }
          },
          {
            name: this.$t('home.absentRate'),
            data: this.monthlyTrendData.absentRates,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: this.isMobile() ? 4 : 6,
            lineStyle: {
              width: this.isMobile() ? 2 : 3
            }
          },
          {
            name: this.$t('home.leaveRate'),
            data: this.monthlyTrendData.leaveRates,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: this.isMobile() ? 4 : 6,
            lineStyle: {
              width: this.isMobile() ? 2 : 3
            }
          }
        ]
      };
      
      this.studentTrendChart.setOption(option);
      
      // 添加到ResizeObserver
      if (this.resizeObserver) {
        this.resizeObserver.observe(trendChartDom);
      } else {
        this.resizeObserver = new ResizeObserver(() => {
          this.resizeCharts();
        });
        this.resizeObserver.observe(trendChartDom);
      }
    },

    isMobile() {
      return window.innerWidth <= 768;
    },

    updateChartOptions() {
      if (this.isStudent) {
        // 更新学生趋势图表
        if (this.studentTrendChart) {
          const isMobile = this.isMobile();
          this.studentTrendChart.setOption({
            title: {
              textStyle: {
                fontSize: isMobile ? 14 : 16
              }
            },
            grid: {
              top: isMobile ? 60 : 40,
              left: isMobile ? 40 : 50,
              right: isMobile ? 10 : 30,
              bottom: isMobile ? 80 : 60
            },
            xAxis: {
              axisLabel: {
                rotate: 45,
                interval: 0
              }
            }
          });
        }
        return;
      }
      
      // 更新折线图配置
      this.lineChart.setOption({
        title: {
          textStyle: {
            fontSize: this.isMobile() ? 14 : 16
          }
        },
        grid: {
          top: this.isMobile() ? 60 : 40,
          left: this.isMobile() ? 40 : 50,
          right: this.isMobile() ? 10 : 30,
          bottom: this.isMobile() ? 60 : 50
        },
        toolbox: {
          orient: this.isMobile() ? 'vertical' : 'horizontal',
          top: this.isMobile() ? 10 : 'top',
          right: this.isMobile() ? 5 : 'auto'
        },
        xAxis: {
          axisLabel: {
            rotate: 45,
            interval: 0
          }
        },
        series: [{
          showSymbol: !this.isMobile()
        }]
      });
      
      // 更新饼图配置
      this.pieChart.setOption({
        title: {
          textStyle: {
            fontSize: this.isMobile() ? 14 : 16
          }
        },
        legend: {
          top: this.isMobile() ? 'bottom' : 'bottom',
          textStyle: {
            fontSize: this.isMobile() ? 12 : 14
          }
        },
        series: [{
          radius: this.isMobile() ? ['35%', '60%'] : ['40%', '70%'],
          label: {
            show: !this.isMobile
          },
          labelLine: {
            show: !this.isMobile
          }
        }]
      });
      
      // 更新柱状图配置
      this.barChart.setOption({
        title: {
          textStyle: {
            fontSize: this.isMobile() ? 14 : 16
          }
        },
        grid: {
          top: this.isMobile() ? 60 : 40,
          left: this.isMobile() ? 40 : 50,
          right: this.isMobile() ? 10 : 30,
          bottom: this.isMobile() ? 80 : 60
        },
        xAxis: {
          axisLabel: {
            rotate: 45,
            interval: 0
          }
        }
      });
    },

    resizeCharts() {
      if (this.isStudent) {
        if (this.studentTrendChart) {
          this.studentTrendChart.resize();
        }
        return;
      }
      
      if(this.lineChart && this.pieChart && this.barChart) {
        this.updateChartOptions();
        this.lineChart.resize();
        this.pieChart.resize();
        this.barChart.resize();
      }
    },

    // 根据时间范围筛选折线图数据
    updateLineChart() {
      if (this.isStudent) return;
      
      this.loading.leaveChart = true;
      
      // 根据选择的时间范围获取数据
      get(`/statistics/leave/distribution/${this.lineChartTimeRange}`)
        .then(res => {
          if (res.code === 200) {
            // 解析API返回的数据
            const resData = res.data;
            const leaveStats = resData.leaveStats || {};
            const dailyStats = leaveStats.dailyStats || {};
            
            // 构建图表数据
            const dates = Object.keys(dailyStats).sort();
            const counts = dates.map(date => dailyStats[date]);
            
            // 更新图表数据
            this.chartData.lineData = {
              x: dates,
              y: counts
            };
            
            // 更新图表显示
            this.lineChart.setOption({
              xAxis: { data: dates },
              series: [{ data: counts }]
            });
          } else {
            this.$message.warning(res.msg || this.$t('home.fetchDistributionFailed'));
          }
        })
        .catch(err => {
          console.error(this.$t('home.fetchDistributionFailed'), err);
          this.$message.error(this.$t('home.fetchDistributionFailed'));
        })
        .finally(() => {
          this.loading.leaveChart = false;
        });
    },
    
    // 更新饼图数据展示
    updatePieChart() {
      if (this.isStudent) return;
      
      let pieData = [];
      
      if (this.pieChartType === 'type') {
        // 获取请假类型分布数据
        get("/statistics/leave/group/distribution").then(res => {
          if (res.code === 200) {
            const leaveData = res.data;
            
            if (leaveData.weekLeaveStats && leaveData.weekLeaveStats.typeStats) {
              const typeStats = leaveData.weekLeaveStats.typeStats;
              pieData = Object.keys(typeStats).map(type => ({
                name: type,
                value: typeStats[type]
              }));
            }
            
            if (pieData.length === 0) {
              pieData = [{ name: this.$t('home.noData'), value: 0 }];
            }
            
            this.chartData.pieData.type = pieData;
            
            this.pieChart.setOption({
              tooltip: {
                formatter: function(params) {
                  return `${params.seriesName}: ${params.name}: ${params.value}${this.$t('home.people')} (${params.percent}%)`;
                }.bind(this)
              },
              series: [{ 
                name: this.$t('home.leaveTypeDistribution'),
                data: pieData,
                label: {
                  formatter: function(params) {
                    return `${params.name}: ${params.value}${this.$t('home.people')}\n${params.percent}%`;
                  }.bind(this)
                }
              }]
            });
          } else {
            this.$message.warning(res.msg || this.$t('home.fetchDistributionFailed'));
          }
        }).catch(err => {
          console.error(this.$t('home.fetchDistributionFailed'), err);
          this.$message.error(this.$t('home.fetchDistributionFailed'));
        });
      } else {
        // 使用按状态分布数据
        get("/statistics/leave/group/distribution").then(res => {
          if (res.code === 200) {
            const leaveData = res.data;
            
            if (leaveData.weekLeaveStats) {
              const statsData = leaveData.weekLeaveStats;
              pieData = [
                { name: this.$t('home.pendingApproval'), value: statsData.pendingCount || 0 },
                { name: this.$t('home.approved'), value: statsData.approvedCount || 0 },
                { name: this.$t('home.rejected'), value: statsData.rejectedCount || 0 }
              ];
            }
            
            if (pieData.length === 0) {
              pieData = [{ name: this.$t('home.noData'), value: 0 }];
            }
            
            this.chartData.pieData.status = pieData;
            
            this.pieChart.setOption({
              tooltip: {
                formatter: function(params) {
                  return `${params.name}: ${params.value}${this.$t('home.people')} (${params.percent}%)`;
                }.bind(this)
              },
              series: [{ 
                name: this.$t('home.leaveStatusDistribution'),
                data: pieData,
                label: {
                  formatter: function(params) {
                    return `${params.name}: ${params.value}${this.$t('home.people')}\n${params.percent}%`;
                  }.bind(this)
                }
              }]
            });
          } else {
            this.$message.warning(res.msg || this.$t('home.fetchDistributionFailed'));
          }
        }).catch(err => {
          console.error(this.$t('home.fetchDistributionFailed'), err);
          this.$message.error(this.$t('home.fetchDistributionFailed'));
        });
      }
    },
    
    // 更新考勤图表
    updateAttendanceChart() {
      if (this.isStudent) return;
      
      // 使用柱状图展示考勤数据
      this.loading.attendanceChart = true;
      const url = this.isAdmin ? '/statistics/attendance/chart' : 
                 `/statistics/attendance/chart?teacherId=${this.userInfo.userId}`;
      
      get(url).then(res => {
        if (res.code === 200) {
          const attendanceData = res.data;
          
          // 使用新的API返回的数据格式
          // 新格式: data包含：statusCounts (对象，每个状态对应一个数组), dates (日期数组)
          const dates = attendanceData.dates || [];
          const statusCounts = attendanceData.statusCounts || {};
          
          // 从statusCounts中获取各状态的数据数组
          const normal = statusCounts.normal || Array(dates.length).fill(0);
          const late = statusCounts.late || Array(dates.length).fill(0);
          const absent = statusCounts.absent || Array(dates.length).fill(0);
          const leave = statusCounts.leave || Array(dates.length).fill(0);
          
          // 保存图表数据
          this.chartData.barData = {
            xAxis: dates,
            normal: normal,
            late: late,
            absent: absent,
            leave: leave
          };
          
          // 根据时间范围筛选并更新图表
          this.filterBarChartData();
        } else {
          this.$message.warning(res.msg || this.$t('attendance.getStatsDataFailed'));
        }
      }).catch(err => {
        console.error(this.$t('attendance.getStatsDataFailed'), err);
        this.$message.error(this.$t('attendance.getStatsDataFailed'));
      }).finally(() => {
        this.loading.attendanceChart = false;
      });
    },
    
    // 根据选择的时间范围过滤柱状图数据
    filterBarChartData() {
      if (!this.chartData.barData.xAxis.length) return;
      
      let { xAxis, normal, leave, late, absent } = this.chartData.barData;
      
      if (this.attendanceTimeRange === 'week' && xAxis.length > 7) {
        const len = xAxis.length;
        xAxis = xAxis.slice(Math.max(0, len - 7), len);
        normal = normal.slice(Math.max(0, len - 7), len);
        leave = leave.slice(Math.max(0, len - 7), len);
        late = late.slice(Math.max(0, len - 7), len);
        absent = absent.slice(Math.max(0, len - 7), len);
      }
      
      this.barChart.setOption({
        xAxis: { data: xAxis },
        series: [
          { name: this.$t('home.normal'), data: normal },
          { name: this.$t('home.leave'), data: leave },
          { name: this.$t('home.late'), data: late },
          { name: this.$t('home.absent'), data: absent }
        ]
      });
    },

    // 新增：获取学生课程详细统计
    loadStudentCoursesStats() {
      if (!this.isStudent || !this.userInfo || !this.userInfo.userId) return Promise.resolve();
      
      this.loading.studentCourses = true;
      return get(`/statistics/dashboard/student/${this.userInfo.userId}/courses`)
        .then(res => {
          if (res.code === 200) {
            this.coursesStats = res.data || [];
          } else {
            this.$message.warning(res.msg || this.$t('attendance.getCourseStatsFailed'));
          }
        })
        .catch(err => {
          console.error(this.$t('attendance.getCourseStatsFailed'), err);
          this.$message.error(this.$t('attendance.getCourseStatsFailed'));
        })
        .finally(() => {
          this.loading.studentCourses = false;
        });
    },
    
    // 新增：获取学生月度考勤趋势
    loadStudentMonthlyTrend() {
      if (!this.isStudent || !this.userInfo || !this.userInfo.userId) return Promise.resolve();
      
      this.loading.studentMonthlyTrend = true;
      return get(`/statistics/dashboard/student/${this.userInfo.userId}/monthly-trend`)
        .then(res => {
          if (res.code === 200) {
            this.monthlyTrendData = res.data || {
              months: [],
              attendanceRates: [],
              lateRates: [],
              absentRates: [],
              leaveRates: []
            };
            
            // 更新趋势图
            if (this.studentTrendChart) {
              this.studentTrendChart.setOption({
                xAxis: { data: this.monthlyTrendData.months },
                series: [
                  { data: this.monthlyTrendData.attendanceRates },
                  { data: this.monthlyTrendData.lateRates },
                  { data: this.monthlyTrendData.absentRates },
                  { data: this.monthlyTrendData.leaveRates }
                ]
              });
            }
          } else {
            this.$message.warning(res.msg || this.$t('attendance.getMonthlyTrendFailed'));
          }
        })
        .catch(err => {
          console.error(this.$t('attendance.getMonthlyTrendFailed'), err);
          this.$message.error(this.$t('attendance.getMonthlyTrendFailed'));
        })
        .finally(() => {
          this.loading.studentMonthlyTrend = false;
        });
    },
    
    // 新增：获取学生学期数据
    loadStudentSemesterData() {
      if (!this.isStudent || !this.userInfo || !this.userInfo.userId) return Promise.resolve();
      
      this.loading.studentStats = true;
      return get(`/statistics/dashboard/student/${this.userInfo.userId}/semester`)
        .then(res => {
          if (res.code === 200) {
            const semesterData = res.data || {};
            
            // 更新仪表盘数据
            this.dashboardData = {
              totalCount: semesterData.courseCount || 0,
              todayCourseCount: semesterData.todayCourseCount || 0,
              leaveCount: semesterData.leaveCount || 0,
              lateCount: semesterData.lateCount || 0,
              absentCount: semesterData.absentCount || 0
            };
            
            // 更新学生统计数据
            this.studentStats = {
              attendanceRate: semesterData.attendanceRate || 0,
              lateRate: semesterData.lateRate || 0,
              absentRate: semesterData.absentRate || 0,
              leaveRate: semesterData.leaveRate || 0
            };
          } else {
            this.$message.warning(res.msg || this.$t('attendance.getSemesterDataFailed'));
          }
        })
        .catch(err => {
          console.error(this.$t('attendance.getSemesterDataFailed'), err);
          this.$message.error(this.$t('attendance.getSemesterDataFailed'));
        })
        .finally(() => {
          this.loading.studentStats = false;
        });
    },

    loadData() {
      this.getUserRole();
      
      // 根据用户角色获取仪表盘数据
      this.loading.dashboard = true;
      
      if (this.isStudent && this.userInfo && this.userInfo.userId) {
        // 学生角色加载专门的统计数据
        Promise.all([
          this.loadStudentSemesterData(),
          this.loadStudentCoursesStats(),
          this.loadStudentMonthlyTrend()
        ]).finally(() => {
          // 确保所有学生数据加载完成后，重置仪表盘loading状态
          this.loading.dashboard = false;
        });
        
      } else {
        let dashboardUrl = '/statistics/dashboard';
        
        if (this.isAdmin) {
          dashboardUrl = '/statistics/dashboard/admin';
        } else if (this.isTeacher) {
          dashboardUrl = `/statistics/dashboard/teacher/${this.userInfo.userId}`;
        }
        
        get(dashboardUrl).then(res => {
          if (res.code === 200) {
            console.log(dashboardUrl);
            const dashboardData = res.data;
            
            // 更新统计卡片数据
            if (this.isAdmin) {
              this.dashboardData = {
                totalCount: dashboardData.totalUserCount || 0,
                todayCourseCount: dashboardData.todayCourseCount || 0,
                leaveCount: dashboardData.weekLeaveStats?.totalCount || 0,
                lateCount: dashboardData.todayStats?.lateCount || 0,
                absentCount: dashboardData.todayStats?.absentCount || 0
              };
            } else if (this.isTeacher) {
              this.dashboardData = {
                totalCount: dashboardData.courseCount || 0,
                todayCourseCount: dashboardData.todayCourseCount || 0,
                leaveCount: dashboardData.weekLeaveStats?.totalCount || 0,
                lateCount: dashboardData.todayStats?.lateCount || 0,
                absentCount: dashboardData.todayStats?.absentCount || 0
              };
            } else {
              // 学生角色
              this.dashboardData = {
                totalCount: dashboardData.courseCount || 0,
                todayCourseCount: dashboardData.todayCourseCount || 0,
                leaveCount: dashboardData.weekLeaveStats?.totalCount || 0,
                lateCount: dashboardData.weekAttendanceStats?.lateCount || 0,
                absentCount: dashboardData.weekAttendanceStats?.absentCount || 0
              };
            }
            
            // 如果是学生角色，直接更新学生统计数据
            if (this.isStudent && dashboardData.weekAttendanceStats) {
              this.studentStats = {
                attendanceRate: dashboardData.weekAttendanceStats.attendanceRate || 0,
                lateRate: (dashboardData.weekAttendanceStats.lateCount / (dashboardData.weekAttendanceStats.totalCount || 1)) * 100 || 0,
                absentRate: (dashboardData.weekAttendanceStats.absentCount / (dashboardData.weekAttendanceStats.totalCount || 1)) * 100 || 0,
                leaveRate: (dashboardData.weekLeaveStats?.totalCount / (dashboardData.weekAttendanceStats.totalCount || 1)) * 100 || 0
              };
            }
            
            // 如果不是学生，则更新图表
            if (!this.isStudent) {
              // 加载请假图表数据
              this.loading.leaveChart = true;
              get("/statistics/leave/group/distribution").then(res => {
                if (res.code === 200) {
                  const leaveData = res.data;
                  
                  // 处理请假状态分布数据
                  if (leaveData.weekLeaveStats) {
                    const statsData = leaveData.weekLeaveStats;
                    
                    // 请假状态分布数据
                    const statusData = [
                      { name: this.$t('home.pendingApproval'), value: statsData.pendingCount || 0 },
                      { name: this.$t('home.approved'), value: statsData.approvedCount || 0 },
                      { name: this.$t('home.rejected'), value: statsData.rejectedCount || 0 }
                    ];
                    
                    this.chartData.pieData.status = statusData;
                    
                    // 更新饼图
                    this.updatePieChart();
                  }
                } else {
                  this.$message.warning(res.msg || this.$t('home.fetchDistributionFailed'));
                }
              }).catch(err => {
                console.error(this.$t('home.fetchDistributionFailed'), err);
                this.$message.error(this.$t('home.fetchDistributionFailed'));
              }).finally(() => {
                this.loading.leaveChart = false;
              });
              
              // 更新考勤图表
              this.updateAttendanceChart();
            }
          } else {
            this.$message.warning(res.msg || this.$t('attendance.getDashboardFailed'));
          }
        }).catch(err => {
          console.error(this.$t('attendance.getDashboardFailed'), err);
          this.$message.error(this.$t('attendance.getDashboardFailed'));
        }).finally(() => {
          this.loading.dashboard = false;
        });
      }
    }
  },
  mounted() {
    this.getUserRole();
    this.loadData();
    this.$nextTick(() => {
      this.initCharts();
    });
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    // 移除所有监听器
    window.removeEventListener('resize', this.resizeCharts);
    if(this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    if(this.lineChart) {
      this.lineChart.dispose();
    }
    if(this.pieChart) {
      this.pieChart.dispose();
    }
    if(this.barChart) {
      this.barChart.dispose();
    }
    if(this.studentTrendChart) {
      this.studentTrendChart.dispose();
    }
  }
}
</script>

<style scoped>
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-card-inner {
  height: auto;
  min-height: 100px;
  transition: all 0.3s;
  padding: 15px;
}

.stat-card-inner:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.stat-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 28px;
  min-height: 28px;
  border-radius: 6px;
  font-size: 16px;
  margin-right: 10px;
  padding: 5px;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1.2;
  overflow: visible;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 400px;
}

.student-stats {
  padding: 10px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.stat-item-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  text-align: center;
}

.stat-item-col {
  margin-bottom: 15px;
}

@media screen and (max-width: 768px) {
  .stat-card-inner {
    min-height: 80px;
    padding: 12px;
  }
  
  .stat-header {
    margin-bottom: 10px;
  }
  
  .stat-icon {
    min-width: 24px;
    min-height: 24px;
    font-size: 14px;
    margin-right: 8px;
    padding: 4px;
  }
  
  .stat-title {
    font-size: 12px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .chart {
    height: 300px;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .chart-header > span {
    margin-bottom: 10px;
  }
  
  .student-stats {
    padding: 5px;
  }
  
  .stat-item {
    margin-bottom: 10px;
  }
  
  .stat-item-title {
    font-size: 12px;
    margin-bottom: 10px;
  }
}

/* 新增：课程统计表格样式 */
.el-table {
  margin-top: 10px;
}

/* 学生月度趋势图表样式增强 */
#studentTrendChart {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

/* 响应式表格容器 */
.responsive-table-container {
  width: 100%;
  overflow-x: auto;
}

/* 移动端表格样式 */
.mobile-table {
  font-size: 12px;
}

.mobile-table th, .mobile-table td {
  padding: 8px 5px;
}

@media screen and (max-width: 576px) {
  .mobile-table .el-progress__text {
    font-size: 10px !important;
  }
  
  .mobile-table .el-table .cell {
    padding-left: 5px;
    padding-right: 5px;
  }
  
  .chart-card .chart-header span {
    font-size: 14px;
  }
}
</style>